package breeze.framework.string;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Deflater;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @author lcf 
 * @email lcf.zdy@163.com
 * @date 2014年8月27日 下午8:56:20
 * @description 
 */
@SuppressWarnings("restriction")
public class Str {

	private static final SimpleDateFormat sdf_datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static final SimpleDateFormat sdf_date = new SimpleDateFormat("yyyy-MM-dd");
	private static final SimpleDateFormat sdf_date2 = new SimpleDateFormat("yyyyMMdd");
	
	public static boolean equalsIgnoreCase(String a,String b,boolean blankMeaningful){
		if(null == a || null == b){
			return false;
		}else if("".equalsIgnoreCase(a) && "".equalsIgnoreCase(b)){
			return blankMeaningful;
		}else{
			return a.equalsIgnoreCase(b);
		}
	}
	
	public static boolean isValid(String...str){
		if(null == str || str.length == 0){
			return false;
		}
		for (int i = 0; i < str.length; i++) {
			if(null != str && !"".equals(str[i])){
				continue;
			}else{
				return false;
			}
		}
		return true;
	}
	
	public static String stringsToString(String[] ss){
		if(ss.length <= 0){
			return "";
		}else{
			String result = Arrays.toString(ss);
			return result.substring(1,result.lastIndexOf("]"));
		}
	}
	
	
	
	//-------------------------------------------------------------
	
	
	/**
	 * 压缩字符串
	 * @param sourcestr String 需要压缩的字符串
	 * @throws UnsupportedEncodingException, IOException, Exception
	 * @return byte[]
	 */
	public static byte[] zipString(String sourcestr) throws UnsupportedEncodingException, IOException, Exception {
		byte[] compressedData = null;
		if (sourcestr == null) {
			throw new Exception("无法压缩字符串，源字符串为 null!");
		}
		try {
			byte[] input = sourcestr.getBytes("GB2312");
			//以最高压缩率建立压缩对象
			Deflater compressor = new Deflater();
			compressor.setLevel(Deflater.BEST_COMPRESSION);
			//给出要压缩的字符
			compressor.setInput(input);
			compressor.finish();
			//根据输入字符的长度建立字节数组输出流
			ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
			//压缩数据
			byte[] buf = new byte[1024];
			while (!compressor.finished()) {
				int count = compressor.deflate(buf);
				bos.write(buf, 0, count);
			}
			bos.close();
			//获得压缩后的字符
			compressedData = bos.toByteArray();
		} catch (UnsupportedEncodingException usee) {
			throw new UnsupportedEncodingException("不支持的字符集错误，相关信息如下：" + usee.getMessage());
		} catch (IOException ioe) {
			throw new IOException("输出流关闭错误，相关信息如下：" + ioe.getMessage());
		} catch (Exception e) {
			throw new Exception("压缩字符串错误，相关信息如下:" + e.getMessage());
		}
		return compressedData;
	}
	
	
	/**
	 *  System.out.println("result: " + buf.toString());// 32位的加密
		System.out.println("result: " + buf.toString().substring(8, 24));// 16位的加密
	 */
	public static String md5Encrypt(String plainText) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes("utf-8"));
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			return buf.toString().toUpperCase();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static byte[] base64Decode(String str){
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			return decoder.decodeBuffer(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String base64Encode(String str){
		return base64Encode(str.getBytes());
	}
	
	public static String base64Encode(byte[] bytes){
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(bytes);
	}

	 public static String toString(Object obj){
		 StringBuffer sbf = new StringBuffer();
		 if(obj instanceof InputStream){
			 BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) obj));
				String inputLine;
				StringBuffer response = new StringBuffer();
				try {
					while ((inputLine = reader.readLine()) != null) {
						response.append(inputLine);
					}
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return response.toString();
		 }else if(obj instanceof List) {
			 sbf.delete(0, sbf.length());
			 List<?> list = (List<?>) obj;
			 for (int i = 0; i < list.size(); i++) {
				Object o = list.get(i);
				if(null == o) {
					sbf.append("");
				}else {
					sbf.append(o.toString());
				}
				sbf.append("\n");
			}
			return sbf.toString();
		 }else if(obj instanceof Object[][]) {
			 Object[][] objs = (Object[][]) obj;
			 sbf.delete(0, sbf.length());
			 for (int i = 0; i < objs.length; i++) {
				for (int j = 0; j < objs[i].length; j++) {
					sbf.append(objs[i][j]).append("|_|");
				}
				sbf.append("\n");
			 }
			 return sbf.toString();
		 }else{
			 return obj.toString();
		 }
	 }

	 
	/**
	 * 简单字符串混淆方法，对应simpleUnconfuse
	 */
	public static String simpleConfuse(String inStr) {
		// String s = new String(inStr);
		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++) {
			a[i] = (char) (a[i] ^ 't');
		}
		String s = new String(a);
		return s;
	}

	/**
	 * 简单解除字符串混淆，对应simpleConfuse
	 */
	public static String simpleUnconfuse(String inStr) {
		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++) {
			a[i] = (char) (a[i] ^ 't');
		}
		String k = new String(a);
		return k;
	}
	
	
	/**
	 * -----------------------String transform to other object--------------------------
	 */
	
	
	/*public static boolean stringToFile(String data, String path) {
		try {
			FileWriter fileWriter = new FileWriter(path);
			fileWriter.write(data);
			fileWriter.flush();
			fileWriter.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}*/
	/*public static boolean stringToFile(String data, URL url) {
		try {
			FileWriter fileWriter = null;
			try {
				fileWriter = new FileWriter(new File(url.toURI()));
			} catch (URISyntaxException e) {
				e.printStackTrace();
			}
			fileWriter.write(data);
			fileWriter.flush();
			fileWriter.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}*/
	
	public static boolean isValidIpAddr(String ip) {
		if (ip.length() < 7 || ip.length() > 15 || "".equals(ip)) {
			return false;
		}
		//判断IP格式和范围
		String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
		Pattern pat = Pattern.compile(rexp);
		Matcher mat = pat.matcher(ip);
		return mat.find();
	}
	
	public static String randomStringId(){
		return UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
	}
	
	//JS数字范围 : −9007199254740992  and 9007199254740992
	public static Long randomLongId(){
		return new Random().nextLong();
	}
	//25位
	public static String randomNumId() {
		return sdf_date2.format(new Date()) + (new Random().nextInt(9999999) + 10000000);
	}
	
	public static String getDatetime(){
		return sdf_datetime.format(new Date());
	}
	
	public static String getCurrentDatePath(){
		String separator = File.separator;
		if(separator.equals("\\")){
			return sdf_date.format(new Date()).replaceAll("-","\\\\") + "\\";
		}else{
			return sdf_date.format(new Date()).replaceAll("-","/") + "/";
		}
	}
	
	/**
	 * TODO 需要改为以{?}为主的遍历,以便为每个{?}提供默认值.
	 */
	public static String replace(String message,String...args) {
		String param;
		for (int i = 0; i < args.length; i++) {
			param = "{" + i + "}";
			if(message.contains(param)){
				if(null == args[i]) {
					message = message.replace(param, "");
				}else {
					message = message.replace(param, args[i]);
				}
			}
		}
		
		for (int i = 0; i < 10; i++) {
			if(message.contains("{" + i + "}")) {
				message = message.replace("{" + i + "}", "");
			}
		}
		return message;
	}
	
	/**
	 * 将一个字符串中的指定片段全部替换，替换过程中不进行正则处理。<br>
	 * 使用String类的replaceAll时要求片段以正则表达式形式给出，有时较为不便，可以转为采用本方法。
	 */
	public static String replaceWithoutRegExp(String str, String subStr,
			String reStr) {
		if (str == null) {
			return null;
		}
		if (subStr == null || subStr.equals("")
				|| subStr.length() > str.length() || reStr == null) {
			return str;
		}
		StringBuffer sb = new StringBuffer();
		int lastIndex = 0;
		while (true) {
			int index = str.indexOf(subStr, lastIndex);
			if (index < 0) {
				break;
			} else {
				sb.append(str.substring(lastIndex, index));
				sb.append(reStr);
			}
			lastIndex = index + subStr.length();
		}
		sb.append(str.substring(lastIndex));
		return sb.toString();
	}
	
	//index从1开始
	public static int indexOf(String source_str,String find_str,int index) {
		if (source_str == null) {
			return -1;
		}
		if (find_str == null || find_str.equals("") || find_str.length() > source_str.length() || source_str == null) {
			return -1;
		}
		
		int pos = 0;
		int count = 0;
		while (true) {
			pos = source_str.indexOf(find_str, pos + 1);
			count++;
			if (pos < 0) {
				break;
			}
			if(count == index) {
				break;
			}
			if(pos > source_str.length()) {
				pos = -1;
				break;
			}
		}
		return pos;
	}
	
	public static String toString(Exception e,int deep) {
		StackTraceElement[] stackElements = e.getStackTrace();
		String msg = ".";
		if(stackElements.length == 2){
			msg = stackElements[1].toString();
		}else if(stackElements.length == 3){
			msg = stackElements[2].toString();
		}else if(stackElements.length > 3){
			if(stackElements.length > deep) {
				msg = stackElements[deep].toString();
			}else {
				msg = stackElements[3].toString();
			}
		}
		
		StringBuffer sbf = new StringBuffer();
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		sbf.delete(0, sbf.length());
		sbf.append("[").append(dateFormat.format(new Date())).append(" ").append(msg).append("] : 捕获异常");
		return sbf.toString();
	}
	
	
	
	
	public static void main(String[] args) {
		//4729CAD411CB6F9A3FD990374DA56DD0
		//8e6d98b90472783cc73c17047ddccf36
//		System.out.println(md5Encrypt("admin123"));
		//E97ABD871EA2793FFA98F430ED268C35
//		System.out.println(md5Encrypt("breeze"));
		String aa = "192.168.1.1";
		System.out.println(aa.substring(0, Str.indexOf("192.168.1.1", ".", 2)));
	}
}
